var $$=function(obj){
	return document.getElementById(obj);
}

window.log = function (){
    return window.console && console.log && Function.apply.call(console.log, console, arguments);
}

var canvas;

var ROOM=function(){
	this.__canvases = [];
	fabric.Object.prototype.transparentCorners = false;
	var containerId='room_canvas';
	canvas = new fabric.StaticCanvas(containerId,{selection:true});
	var container=$$(containerId);
	//fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
	var context= canvas.getContext("2d");
	var devicePixelRatio = window.devicePixelRatio || 1;
	var backingStoreRatio = context.webkitBackingStorePixelRatio ||
		context.mozBackingStorePixelRatio ||
		context.msBackingStorePixelRatio ||
		context.oBackingStorePixelRatio ||
		context.backingStorePixelRatio || 1;
	//context.translate(0.5, 0.5);
	var ratio = devicePixelRatio / backingStoreRatio;
	var posi={};
	var locs={};
	var seats={};
	var INVALID=-99999;
	var currZoom=1;
	// var option={scale:45*ratio,marginLeft:14,marginTop:2};
	var option=(function () {
		var ht=container.getAttribute("height");
		var wd=container.getAttribute("width");
		var realHeight=16;
		var realWidth=10;
		var scale=Math.min(ht/realHeight,wd/realWidth);
		return {scale:scale,marginLeft:(wd/scale-realWidth)/2-2,marginTop:(ht/scale-realHeight)/2+1.5};
	})();

	canvas.on("mouse:move",function (evt) {
		log(evt.target);
	});

/*
	container.on("mousewheel", function () {
		var dt=event.wheelDelta/40;
		currZoom=dt>0?(currZoom+0.2):(currZoom-0.2);
		if(currZoom<0.2){
			currZoom=0.2;
		}else if(currZoom>9){
			currZoom=9;
		}
		canvas.zoomToPoint(new fabric.Point(500, 300),currZoom);
		log(currZoom);
		//event.stopPropagation();
		return false;
	});
*/
	var Block=function (opt,tits){
		var bk = new fabric.Rect({
		    top : opt.top*option.scale,
		    left : opt.left*option.scale,
		    width : opt.width*option.scale,
		    height : opt.height*option.scale,
		    fill : opt.color
		});
		bk.hasControls=bk.hasBorders=bk.selectable=true;
		canvas.add(bk);

		var seatWidth=1.25;
		var seatHeight=1.46;
		seats[tits[0]]=new Seat({"top":opt.top,"left":opt.left+seatWidth,"width":seatWidth,"height":seatHeight},tits[0]);
		seats[tits[1]]=new Seat({"top":opt.top+seatHeight*2,"left":opt.left+seatWidth,"width":seatWidth,"height":seatHeight},tits[1]);

		var ps0={x:opt.left+seatWidth*1.5,y:opt.top+seatHeight*0.5};
		var ps1={x:opt.left+seatWidth*1.5,y:opt.top+seatHeight*2.5};
		posi[tits[0]]=ps0;
		posi[tits[1]]=ps1;

	}

	var Seat=function(opt,tit){
		var seatColor="#00B050";
		var bk = new fabric.Rect({
		    top : opt.top*option.scale,
		    left : opt.left*option.scale,
		    width : opt.width*option.scale,
		    height : opt.height*option.scale,
		    fill : seatColor
		});
		canvas.add(bk);

		var seat = new fabric.Text(tit,{
		    top : (opt.top+0.4)*option.scale,
		    left : (opt.left+0.2)*option.scale,
		    width : opt.width*option.scale,
		    height : opt.height*option.scale,
		    fontSize : 0.4*option.scale,
		    fill : "#000",
		    fontFamily: 'Arial, Helvetica, sans-serif',
		    textAlign:"center"
		});
		canvas.add(seat);
		return bk;
	}
	
	var blockWidth=2.5;
	var blockHeight=5.84;
	var blockBackColor="#BFBFBF";

	new Block({"top":option.marginTop,"left":1.5+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A001","A002"]);
	new Block({"top":7.34+option.marginTop,"left":1.5+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A003","A004"]);
	new Block({"top":option.marginTop,"left":5.1+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A005","A006"]);
	new Block({"top":7.34+option.marginTop,"left":5.1+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A007","A008"]);
	new Block({"top":option.marginTop,"left":8.8+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A009","A010"]);
	new Block({"top":7.34+option.marginTop,"left":8.8+option.marginLeft,"width":blockWidth,"height":blockHeight,"color":blockBackColor},["A011","A012"]);

	function fetchMaxSignalSeat(pts,usedLoc){
		if(!pts||pts.length==0){
			return null;
		}
		if(pts.length==1){
			return pts[0];
		}
		var max=INVALID;
		var idx=0;
		for(var i=0;i<pts.length;i++){
			if(usedLoc.contains(i)){
				continue;
			}
			var p=parseFloat(pts[i],10);
			if(max==INVALID){
				max=p;
				idx=i;
				continue;
			}
			if(max<p){
				max=p;
				idx=i;
			}
		}
		return {"max":max,"index":idx};
	}

	function calcLoc(locName){
		var pt={};
		var seat=seats[locName];
		pt.x=seat.left+seat.width/2;
		pt.y=seat.top+seat.height/2;
		return pt;
	}

	function fetchMinRes(sortedData,maxAbs,max,idx){
		var res=new Array();
		for(var k=0;k<sortedData.length;k++){
			if(Math.abs(max-sortedData[k].value[idx])<=maxAbs){
				res.push(sortedData[k].name);
				// log(sortedData[k].name,sortedData[k].value[idx]);
			}
		}
		return res;
	}
	
	function clearCanvas() {
		if(!locs){
			return;
		}
		for(var imei in locs){
			if(locs[imei]&&locs[imei].length>0){
				for(var i=0;i<locs[imei].length;i++){
					canvas.remove(locs[imei][i]);
				}
			}
		}
	}

	function clearCanvas4Imei(imei) {
		if(locs[imei]&&locs[imei].length>0){
			for(var i=0;i<locs[imei].length;i++){
				canvas.remove(locs[imei][i]);
			}
		}
	}

	var location=function(pts,imei,name,grade,isDpt){
		var locName;
		var usedLoc=new Array();
		if(!isDpt){
			clearCanvas();
		}

		var mp = fetchMaxSignalSeat(pts, usedLoc);
		for(var m=0;m<wifiData.length;m++){
			wifiData[m].abs1=Math.abs(wifiData[m].value[mp.index]-mp.max);
		}
		usedLoc.push(mp.index);

		var mp2 = fetchMaxSignalSeat(pts, usedLoc);
		for(var m=0;m<wifiData.length;m++){
			wifiData[m].abs2=Math.abs(wifiData[m].value[mp2.index]-mp2.max);
		}

		var sortedData = wifiData.slice(0,wifiData.length).sort(function (a, b) {
			return a.abs1 - b.abs1;
		});
		var sortedData2 = wifiData.slice(0,wifiData.length).sort(function (a, b) {
			return a.abs2 - b.abs2;
		});

		var array1=new Array();
		var array2=new Array();
		for(var m=0;m<sortedData.length;m++){
			array1.push(sortedData[m].name);
			// log(array1.toString());
			if(Array.intersect(array1,array2).length>0){
				locName=sortedData[m].name;
				break;
			}
			array2.push(sortedData2[m].name);
			// log(array2.toString());
			if(Array.intersect(array1,array2).length>0){
				locName=sortedData2[m].name;
				break;
			}
		}

		if(!locName){
			log("未能定位！");
			return;
		}
		var pt=calcLoc(locName);
		clearCanvas4Imei(imei);
		var radius=8;
		var leftL=pt.x-radius/2;
		var topL=pt.y-radius/2;

		var label = new fabric.Text(name,{
			top : topL-(0.57+0.85)*option.scale-2,
			left : leftL-name.length*0.15*option.scale,
			width : option.scale,
			height : 0.85*option.scale,
			fontSize : 0.57*option.scale,
			fill : "#FFF",
			backgroundColor: "#F00",
			fontFamily: 'Arial, Helvetica, sans-serif',
			textAlign:"center"
		});
		if(!locs[imei]){
			locs[imei]=[];
		}
		locs[imei].push(label);

		var grade=new fabric.Triangle({
			top:topL-6,
			left:leftL+0.57*option.scale,
			width:0.64*option.scale,
			height:0.57*option.scale,
			fill:"#F00",
			angle:180,
			strokeWidth:1,
			stroke:"#FFF"
		});
		locs[imei].push(grade);
		canvas.add(grade);
		canvas.add(label);
	}

	this.__canvases.push(canvas);
	return {"location":location,"canvas":canvas};
};

function parseWifis(wf) {
	var wfs=new Array();
	var od=wf.split(",");
	for(var s=0;s<od.length;s=s+2){
		if(od[s]==null||od[s]==""){
			continue;
		}
		if(od[s].indexOf("XI")==-1){
			continue;
		}
		var w={};
		w.n=od[s];
		w.v=parseFloat(od[s+1]);
		wfs.push(w);
	}
	wfs=wfs.sort(function (a, b) {
		return a.n<b.n?-1:(a.n==b.n?0:1);
	});
	var res=new Array();
	for(var s=0;s<wfs.length;s++){
		res.push(wfs[s].v);
	}
	return res;
}

var wifiData;
var room;

function initRoomMap() {
	//$.getJSON(getContextPath()+"/wifiLoc/base",function (data) {
		if(!Array.isArray(data)){
			return;
		}
		wifiData=new Array();
		for(var i=0;i<data.length;i++){
			var item={};
			item.name="A"+data[i].seq;
			item.value=parseWifis(data[i].wifis);
			wifiData.push(item);
		}
		if(!wifiData||wifiData.length==0){
			return;
		}
		//$("#map_canvas").hide();
		//$("#room_canvas").hide();
		room=ROOM();
		if(JSON){
			log(JSON.stringify(wifiData));
		}
	//});
}

(function() {
	fabric.util.addListener(fabric.window, 'load', function() {
		var canvas = this.__canvas || this.canvas,
			canvases = this.__canvases || this.canvases;

		canvas && canvas.calcOffset && canvas.calcOffset();

		if (canvases && canvases.length) {
			for (var i = 0, len = canvases.length; i < len; i++) {
				canvases[i].calcOffset();
			}
		}
	});
})();

function testLoc(){
	initRoomMap();
	var dt={
		loc:"XI02,-62,XI01,-66,XI04,-76,XI03,-82,22,0.50,1,",
		termImei:"111111111111242",
		termName:"手铐室内定位"
	};
	var lloc=parseWifis(dt.loc);
    log("当前终端定位：",lloc.slice(0,lloc.length).join(","),"imei：",dt.termImei,"名称：",dt.termName);
    room.location(lloc,dt.termImei,dt.termName,"普");
}